import sys
import subprocess

storage = 'fdfs_storaged'
storagePath = '/etc/fdfs/storage.conf'
tracker = 'fdfs_trackerd'
trackerPath = '/etc/fdfs/tracker.conf'

# 检查程序是否在运行
def IsProcessRunning(processName):
    result = subprocess.run(['pgrep', '-f', processName])
    return result.returncode == 0

# 启动tracker程序
def StartTracker():
    if IsProcessRunning(tracker):
        print('Tracker is already running, not start again.')
    else:
        result = subprocess.run(['sudo', tracker, trackerPath])
        if result.returncode != 0:
            print("Start tracker failed.")
        else:
            print("Start tracker success.")

# 启动storage程序
def StartStorage():
    if IsProcessRunning(storage):
        print('Storage is already running, not start again.')
    else:
        result = subprocess.run(['sudo', storage, storagePath])
        if result.returncode != 0:
            print("Start storage failed.")
        else:
            print("Start storage success.")

# 停止服务
def StopService():
    subprocess.run(['sudo', tracker, trackerPath, 'stop'])
    subprocess.run(['sudo', storage, storagePath, 'stop'])

def main():
    if len(sys.argv) < 2:
        print('Please input the operation.')
        sys.exit(0)
    
    operation = sys.argv[1]
    if operation == 'storage':
        StartStorage()
    elif operation == 'tracker':
        StartTracker()
    elif operation == 'all':
        StartTracker()
        StartStorage()
    elif operation == 'stop':
        StopService()
    else:
        print('Operation is failed, please input the correct operation.')

if __name__ == '__main__':
    main()